package com.haizhi.crm.search.service.impl;

import com.haizhi.crm.common.context.Resource;
import com.haizhi.crm.common.json.JSONUtils;
import com.haizhi.crm.common.util.FileUtils;
import com.haizhi.crm.search.constant.AtlasType;
import com.haizhi.crm.search.service.GdbTemplateService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by chengmo on 2018/6/14.
 */
@Service
public class GdbTemplateServiceImpl implements GdbTemplateService {
    private static final String TEMPLATE_DIR = "atlas";
    private static Map<AtlasType, String> TEMPLATES = new ConcurrentHashMap<>();

    @PostConstruct
    public void loadTemplates() {
        String path = Resource.getPath() + TEMPLATE_DIR;
        List<File> files = FileUtils.getFiles(path);
        for (File file : files) {
            String template = FileUtils.readTxt(file.getPath());
            String str = StringUtils.substringBefore(file.getName(), "_" );
            int serialNumber = NumberUtils.toInt(str);
            TEMPLATES.put(AtlasType.from(serialNumber), template);
        }
    }

    @Override
    public Map<String, Object> getAtlasTemplate(AtlasType atlasType) {
        String template = TEMPLATES.get(atlasType);
        return JSONUtils.jsonToMap(template);
    }
}
